import 'package:flutter/material.dart';
import '../services/database_service.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/timezone.dart' as tz;

class SettingsScreen extends StatefulWidget {
  const SettingsScreen({super.key});

  @override
  _SettingsScreenState createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  final DatabaseService _databaseService = DatabaseService();
  final FlutterLocalNotificationsPlugin _notificationsPlugin = FlutterLocalNotificationsPlugin();
  
  int _dailyGoal = 10;
  TimeOfDay _reminderTime = const TimeOfDay(hour: 20, minute: 0);
  bool _notificationsEnabled = false;
  bool _smartReminderEnabled = false;

  @override
  void initState() {
    super.initState();
    _loadSettings();
    _initializeNotifications();
  }

  Future<void> _loadSettings() async {
    final settings = await _databaseService.getStudySettings();
    setState(() {
      _dailyGoal = settings['dailyGoal'];
      _smartReminderEnabled = settings['smartReminderEnabled'] ?? false;
      if (settings['reminderTime'] != null) {
        final timeParts = settings['reminderTime'].split(':');
        _reminderTime = TimeOfDay(
          hour: int.parse(timeParts[0]),
          minute: int.parse(timeParts[1]),
        );
      }
    });
  }

  Future<void> _saveSettings() async {
    await _databaseService.updateStudySettings(
      dailyGoal: _dailyGoal,
      reminderTime: '${_reminderTime.hour}:${_reminderTime.minute}',
      smartReminderEnabled: _smartReminderEnabled,
    );
  }

  Future<void> _initializeNotifications() async {
    const initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher');
    const initializationSettingsDarwin = DarwinInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestSoundPermission: true,
    );
    const initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsDarwin,
    );
    await _notificationsPlugin.initialize(initializationSettings);
    
    // 检查通知权限
    final notificationSettings = await _notificationsPlugin.resolvePlatformSpecificImplementation<
      IOSFlutterLocalNotificationsPlugin>()?.requestPermissions(
        alert: true,
        badge: true,
        sound: true,
      );
    setState(() {
      _notificationsEnabled = notificationSettings ?? false;
    });
  }

  tz.TZDateTime _nextInstanceOfTime(TimeOfDay time) {
    final now = tz.TZDateTime.now(tz.local);
    var scheduledDate = tz.TZDateTime(
      tz.local,
      now.year,
      now.month,
      now.day,
      time.hour,
      time.minute,
    );

    if (scheduledDate.isBefore(now)) {
      scheduledDate = scheduledDate.add(const Duration(days: 1));
    }

    return scheduledDate;
  }


  Future<void> _scheduleNotification() async {
    if (!_notificationsEnabled) return;

    await _notificationsPlugin.zonedSchedule(
      0,
      '单词学习提醒',
      '今天的单词还没有复习哦，目标：$_dailyGoal个单词',
      _nextInstanceOfTime(_reminderTime),
      const NotificationDetails(
        android: AndroidNotificationDetails(
          'word_reminder',
          '单词提醒',
          channelDescription: '每日单词学习提醒',
          importance: Importance.high,
          priority: Priority.high,
        ),
        iOS: DarwinNotificationDetails(),
      ),
      androidAllowWhileIdle: true,
      uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
      matchDateTimeComponents: DateTimeComponents.time,
    );
  }

  Future<void> _selectTime(BuildContext context) async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: _reminderTime,
    );
    if (picked != null && picked != _reminderTime) {
      setState(() {
        _reminderTime = picked;
      });
      await _saveSettings();
      await _scheduleNotification();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('学习设置'),
      ),
      body: ListView(
        children: [
          ListTile(
            title: const Text('启用智能复习提醒'),
            trailing: Switch(
              value: _smartReminderEnabled,
              onChanged: (value) {
                setState(() {
                  _smartReminderEnabled = value;
                });
                _saveSettings();
              },
            ),
          ),
          ListTile(
            title: const Text('每日学习目标'),
            subtitle: Text('$_dailyGoal 个单词'),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                IconButton(
                  icon: const Icon(Icons.remove),
                  onPressed: () async {
                    if (_dailyGoal > 1) {
                      setState(() {
                        _dailyGoal--;
                      });
                      await _saveSettings();
                    }
                  },
                ),
                Text('$_dailyGoal'),
                IconButton(
                  icon: const Icon(Icons.add),
                  onPressed: () async {
                    setState(() {
                      _dailyGoal++;
                    });
                    await _saveSettings();
                  },
                ),
              ],
            ),
          ),
          ListTile(
            title: const Text('提醒时间'),
            subtitle: Text('${_reminderTime.format(context)}'),
            trailing: Switch(
              value: _notificationsEnabled,
              onChanged: (bool value) async {
                if (value) {
                  // 请求通知权限
                  final notificationSettings = await _notificationsPlugin
                      .resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
                      ?.requestPermissions(
                        alert: true,
                        badge: true,
                        sound: true,
                      );
                  setState(() {
                    _notificationsEnabled = notificationSettings ?? false;
                  });
                  if (_notificationsEnabled) {
                    await _scheduleNotification();
                  }
                } else {
                  await _notificationsPlugin.cancel(0);
                  setState(() {
                    _notificationsEnabled = false;
                  });
                }
              },
            ),
            onTap: () => _selectTime(context),
          ),
        ],
      ),
    );
  }
}
